from flask import Flask
from flasgger import Swagger
from flask_cors import CORS


def create_app():
    app = Flask(__name__)
    
    # 严格CORS配置：仅允许前端 http://localhost:8080 访问
    CORS(app, resources={
        r"/api/*": {"origins": "http://localhost:8080"},
        r"/docs/*": {"origins": "http://localhost:8080"},  # 允许前端访问Swagger
        r"/flasgger_static/*": {"origins": "http://localhost:8080"}  # Swagger静态资源
    })

    # Swagger配置（保持不变）
    app.config['SWAGGER'] = {
        'title': '舆情爬虫API',
        'uiversion': 3,
        'specs_route': '/docs/',
        'static_url_path': '/flasgger_static',
        'specs': [{
            'endpoint': 'apispec',
            'route': '/apispec.json',
            'rule_filter': lambda rule: True,
            'model_filter': lambda tag: True,
        }],
        'template_files': ['docs/crawler_docs.yml', 'docs/generate_docs.yml']  # 包含所有API文档
    }
    
    Swagger(app)  # 必须在注册蓝图前初始化
    
    from .routes import crawler_bp, generate_bp
    app.register_blueprint(crawler_bp, url_prefix='/api/v1')
    app.register_blueprint(generate_bp, url_prefix='/api/v1')
    
    return app